<?php

namespace mpend\modules\passport\controllers;

use Yii;
use mpend\components\Controller;
use mpend\models\AuthWechatForm;
use common\models\user\UserConnect;
use common\helpers\Url;

/**
 * 短信验证码校验
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class WechatController extends Controller {

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            '*' => ['POST'],
        ];
    }

    /**
     * 校验短信验证码
     * @return mixed
     */
    public function actionIndex() {
        $autoLoginUrl = Url::to(['/passport/wechat/authorized'], true);
        $authUrl = Yii::$app->wechat->getOauth2AuthorizeUrl($autoLoginUrl, 'authorize', 'snsapi_userinfo');
        return $this->redirect($authUrl);
    }

    /**
     * 校验短信验证码
     * @return mixed
     */
    public function actionAuth() {
        $model = new AuthWechatForm();
        $model->client = UserConnect::CLIENT_WECHAT;
        Yii::error(Yii::$app->request->post());
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('缺少微信授权信息');
        }
        return $model->connect();
    }

    /**
     * 校验短信验证码
     * @return mixed
     */
    public function actionAuthorized() {
//        $code = Yii::$app->request->get('code');
//        if (!$code) {
//            throw new \yii\web\NotAcceptableHttpException("授权信息不正确");
//        }
//        $wechat = Yii::$app->wechat;
//        $data = $wechat->getOauth2AccessToken($code);
//        $wechatUserInfo = $wechat->getSnsUserInfo($data['openid'], $data['access_token']);
//
//        $model = new WechatRegister();
//        $model->setAttributes($wechatUserInfo);
//
//        $user = $model->signup($msg);
//        if ($user == false) {
//            throw new \yii\web\UnauthorizedHttpException("登录授权失败！" . $msg);
//        }
//
//        return $this->goBack();
        $model = new WechatAuthForm();
        $model->client = UserConnect::CLIENT_WECHAT;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('缺少微信授权信息');
        }
        return $model->connect();
//
//        $code = Yii::$app->request->get('code');
//        if (!$code) {
//            throw new \yii\web\NotAcceptableHttpException("授权信息不正确");
//        }
//
//        $wechat = Yii::$app->wechat;
//        $data = $wechat->getOauth2AccessToken($code);
//        $wechatUserInfo = $wechat->getSnsUserInfo($data['openid'], $data['access_token']);
//
//        $model = new WechatRegister();
//        $model->setAttributes($wechatUserInfo);
//
//        $user = $model->signup($msg);
//        if ($user == false) {
//            throw new \yii\web\UnauthorizedHttpException("登录授权失败！" . $msg);
//        }
//
//        return $this->goBack();
//        return Yii::$app->request->post();
    }

}
